import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './styles/index.scss'
import './permission' // 权限控制

const app = createApp(App)

// 注册ElementPlus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(router)
app.use(store)
app.use(ElementPlus)

app.mount('#app')

// 在路由错误处理中添加DOM校验
// 在app.mount之前添加
if (process.env.NODE_ENV === 'development') {
  window.$router = router
  window.$store = store
}

// 修改后的错误处理
router.onError((error) => {
  console.error('[路由错误]', error)
  if (error.message.includes('Cannot read')) {
    setTimeout(() => {
      router.push(router.currentRoute.value.fullPath)
    }, 500)
  }
})

// 增强全局错误处理
app.config.errorHandler = (err, instance, info) => {
  console.error('全局捕获:', { 
    err, 
    info,
    route: router.currentRoute.value,
    component: instance?.$options?.name
  })
  if (err.message.includes('path')) {
    console.warn('执行路由恢复操作...')
    router.push(router.currentRoute.value.fullPath)
  }
}

// router.afterEach((to) => {
//   console.log('导航完成:', {
//     path: to.path,
//     matched: to.matched.map(m => m.path)
//   })
// })
